import path from 'path'
import shell from 'shelljs'

export default async function (fastify, opts) {
  if (!shell.which('volta')) {
    shell.exec(`curl https://get.volta.sh | bash`)
  }

  fastify.get('/', async function (request, reply) {
    return { code: 200, message: 'ok' }
  })

  fastify.post('/update', async function (request, reply) {
    try {
      reply.send({ code: 200, message: 'ok' })

      fastify.log.info('/update params : ' + JSON.stringify(request.query))

      const { branch, form, to, node } = request.query

      if (!form || !to) return { code: 400, message: '路径不存在' }

      if (!shell.which('git')) {
        return { code: 400, message: '没有git服务' }
      }

      //切换路径
      shell.cd(form)
      //切换分支
      if (branch) {
        shell.exec(`git checkout ${branch}`)
      }
      //切换node版本
      if (node) {
        shell.exec(`volta pin node@${node}`)
      }
      // 查看node 版本
      shell.exec(`node -v`)

      // 更新
      shell.exec(`git pull`)
      // 安装依赖
      shell.exec(`npm install`)
      // 打包
      shell.exec(`npm run build`)
      // 复制文件
      shell.cp('-R', path.join(form, 'dist') + '/*', to)

      fastify.log.info(`所有命令执行完毕`)
    } catch (error) {
      fastify.log.info(`执行失败: ` + error.toString())
    }
  })
}
